#A script for sending test messages
#Takes a command line argument for the amount of messages you want to send
#supports -d and -r options
#-d sends static data over a period of time
#-r sends realistic, dynamically generated data over a period of time
#
#Written by Tony

import pika, optparse, argparse, time, json, random

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='A_Queue')

argparser = argparse.ArgumentParser(argument_default=1)
parser = optparse.OptionParser()
argparser.add_argument('integer', type=int)
parser.add_option("-d", action="store_true", dest="dynamic")
parser.add_option("-r", action="store_true", dest="realistic")
(options, args) = parser.parse_args()

serverTemplate = {"total_tracker_download": 0, "num_unchoked": 0, "total_payload_upload": 0, "upload_rate": 0, "payload_upload_rate": 0, "num_peers": 0, "tracker_download_rate": 0, "tracker_upload_rate": 0, "dht_download_rate": 0, "ip_overhead_upload_rate": 0, "total_ip_overhead_download": 0, "total_tracker_upload": 0, "total_dht_download": 0, "total_ip_overhead_upload": 0, "num_torrents": 0, "total_payload_download": 0, "download_rate": 0, "timestamp": "", "allowed_upload_slots": 500, "payload_download_rate": 0, "peer_id": "-DH2000-F1.QNdo)EKsr", "total_download": 0, "ip_overhead_download_rate": 0, "dht_upload_rate": 0, "total_dht_upload": 0, "total_upload": 0}
torrentTemplate = {"peers" : [], "timestamp": "0", "interval": 1000, "name": "", "info_hash": "99d245934c812c75047e6541f89a1a39f80c6eb5", "transferred": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
peerTemplate = {"connection_type": "standard_bittorrent", "payload_down_speed": 0, "ip_addr": "192.168.29.1", "down_speed": 0, "rtt": 0, "up_speed": 0, "remote_dl_rate": 0, "failcount": 0, "source": ["incoming"], "payload_up_speed": 0, "client": "Transmission 2.42", "flags": ["choked", "remote_choked", "supports_extensions"], "downloading_progress": 0, "progress": 0.0, "load_balancing": 0, "ip_port": 65160}

torrents = ['Scenery-1.0.1', 'RHEL6.0-20100414.0-AP-i386-DVD1.iso', 'wpclipart-8.0.exe', "pgdvd072006.iso", "M57-Scenario-All-Materials-E01", "M57-Scenario-Pat-Drive-Images", "M57-Scenario-Police-Evidence-E01", "M57-Scenario-Charlie-Drive-Images-E01", "FlightGear-data-2.4.0.tar.bz2", "M57-Scenario-Terry-Drive-Images-E01", "pc-os-od2009.iso", "engarde-community-3.0.22.i686.iso"]
peers = ['192.168.29.1', '192.168.45.1', '172.16.254.1', '183.24.168.1']
active_peers = list(peers)
active_torrents = ['Scenery-1.0.1', 'RHEL6.0-20100414.0-AP-i386-DVD1.iso', 'wpclipart-8.0.exe']
torrent_peers = {torrents[0] : [[peers[0], 0], [peers[1], 0], [peers[3], 0]], torrents[1] : [[peers[2], 0], [peers[3], 0]], torrents[2] : [[peers[0], 0], [peers[1],0] , [peers[2], 0], [peers[3],0]]}
triggers = [500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500]
in_next = 3
next_trigger = 0


if (options.dynamic):
    f = open('example_stats.txt')
    for i in range(int(args[0])):
        jsonMessage = f.readline()
        channel.basic_publish(exchange='', routing_key='A_Queue', body=jsonMessage, properties=pika.BasicProperties(content_type="application/json"))
        if ((i % 10) == 0):
            time.sleep(1)
    else:
        f.close()
elif (options.realistic):
    messages = 0
    serv_total = 0
    while(messages < int(args[0])):
        begin = time.time()
        serv_down = []
        serv_up = []

        
        for torr in active_torrents:
            torr_down = []
            torr_up = []
            torr_peers = list(torrent_peers[torr])
            for (i,peer) in enumerate(torr_peers):
                peerMessage = dict(peerTemplate)
                peer[1] += random.random()
                if (peer[1] > 100):
                    peer[1] = 0
                    if ((next_trigger < len(triggers)) & (in_next < len(torrents))):
                        if (messages > triggers[next_trigger]):
                            active_torrents.append(torrents[in_next])
                            in_next += 1
                            next_trigger += 1
                            tmp = list(peers)
                            random.shuffle(tmp)
                            torrent_peers.update({active_torrents[-1] : [[tmp.pop(), 0], [tmp.pop(), 0], [tmp.pop(), 0]]})
                    
                torr_down.append(random.randint(5000, 100000))
                torr_up.append(random.randint(5000, 100000))
                peerMessage['ip_addr'] = peer[0]
                peerMessage['payload_down_speed'] = torr_up[-1]
                peerMessage['payload_up_speed'] = torr_down[-1]
                peerMessage['progress'] = peer[1]
                torr_peers[i] = peerMessage

                
            torrMessage = dict(torrentTemplate)
            torr_down.append(random.randint(500, 25000))
            torrMessage['name'] = torr
            torrMessage['timestamp'] = time.time()
            torrMessage['transferred'][0] = sum(torr_up)
            torrMessage['transferred'][5] = torr_down[-1]
            torrMessage['peers'] = torr_peers
            jsonMessage = json.dumps(torrMessage)
            channel.basic_publish(exchange='', routing_key='A_Queue', body=jsonMessage, properties=pika.BasicProperties(content_type="application/json")) 
            messages += 1
            
            serv_up.append(sum(torr_up))
            serv_down.append(sum(torr_down))
        
        servMessage = dict(serverTemplate)
        serv_total += sum(serv_up)
        servMessage['num_peers'] = len(active_peers)
        servMessage['num_torrents'] = len(active_torrents)
        servMessage['timestamp'] = time.time()
        servMessage['payload_upload_rate'] = sum(serv_up)
        servMessage['payload_download_rate'] = sum(serv_down)
        servMessage['total_payload_upload'] = serv_total 
        jsonMessage = json.dumps(servMessage)
        channel.basic_publish(exchange='', routing_key='A_Queue', body=jsonMessage, properties=pika.BasicProperties(content_type="application/json"))
        messages += 1                
        
        end = 1 - (time.time() - begin)
        if end > 0: time.sleep(end)
        
else:
    f = open('example_stats.txt')
    for i in range(int(args[0])):
        jsonMessage = f.readline()
        channel.basic_publish(exchange='', routing_key='A_Queue', body=jsonMessage, properties=pika.BasicProperties(content_type="application/json"))
    else:
        f.close()  


connection.close()